import os

from alipay import AliPay
from django import http
from django.conf import settings
from django.shortcuts import render

# Create your views here.
from django.views import View
from apps.orders.models import OrderInfo
from apps.payment.models import Payment
from meiduo_mall.utils.views import LoginRequiredJSONMixin


class PaymentView(LoginRequiredJSONMixin,View):
    """支付订单功能"""
    def get(self,request,order_id):
        # 查询要支付的订单
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id,user=user,status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except Exception as e:
            return http.JsonResponse({"code":400,"errmsg":"订单信息错误"})

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            # 默认回调url
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/alipay_public_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),"keys/app_private_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG,

        )

        # 生成登录支付宝连接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 响应登录支付宝连接
        # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return http.JsonResponse({"code":0,"errmsg":"OK","alipay_url":alipay_url})


class PaymentStatusView(View):
    """保存订单支付结果"""
    def get(self,request):
        # 获取前端传入的请求参数
        query_dict = request.GET
        data = query_dict.dict()

        # 获取并从请求参数中剔除signature
        signature = data.pop("sign")

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),"keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 校验这个重定向是否是alipay重定向过来的
        success = alipay.verify(data,signature)
        if success:
           # 校验通过
           # 4.存入 数据表
           Payment.objects.create(order=data.get('out_trade_no'),trade_id=data.get('trade_no'),)
           # 5. 更改订单状态 为待评价
           OrderInfo.objects.filter(pk=data.get('out_trade_no'),
                                    status = OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT'])
           return http.JsonResponse({"code":400,"errmsg":"OK","trade_id":data.get('trade_no')})
        else:
            return http.JsonResponse({"code":0,"errmsg":"非法交易"})